package com.yycx.module.bus.provider.handler.report;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.module.export.ExportField;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.mybatis.interceptor.ExportInterceptor;
import com.yycx.common.mybatis.interceptor.PageInterceptor;
import com.yycx.common.mybatis.model.PageParams;
import com.yycx.common.mybatis.query.CriteriaQuery;
import com.yycx.common.security.OpenHelper;
import com.yycx.common.utils.DateUtils;
import com.yycx.common.utils.RedisUtils;
import com.yycx.module.bus.client.entity.*;
import com.yycx.module.bus.client.enums.SaleTypeEnum;
import com.yycx.module.bus.provider.service.*;
import com.yycx.module.system.provider.service.SysBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务明细表
 *
 * @author zyf
 */
@Component("orderDetailsReportHandler")
public class OrderDetailsReportHandler implements PageInterceptor<BusOrderDetails>, ExportInterceptor {


    @Autowired
    private BusPaymentService paymentService;


    @Autowired
    private BusOrderService orderService;

    @Autowired
    private BusInvoiceunitService invoiceunitService;

    @Autowired
    private SysBankService bankService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private BusOrderDetailsService detailsService;


    @Override
    public void prepare(CriteriaQuery<BusOrderDetails> cq, PageParams pageParams, EntityMap params) {
        String orderNo = params.get("orderNo");
        String supplierBondState = params.get("supplierBondState");
        Long companyId = params.getLong("companyId");
        Integer errorType = params.getInt("errorType", 0);
        String customReturnState = params.get("customReturnState");
        String supplierRefundState = params.get("supplierRefundState");
        String customBondState = params.get("customBondState");
        String saleType = params.get("saleType");
        String settleState = params.get("settleState");
        String beginDate = params.get("beginDate");
        String endDate = params.get("endDate");
        String refundDate1 = params.get("refundDate1");
        String refundDate2 = params.get("refundDate2");
        String returnDate1 = params.get("returnDate1");
        String returnDate2 = params.get("returnDate2");
        cq.likeLeft(FlymeUtils.isNotEmpty(params.get("orderNo")), "orderNo", orderNo);
        cq.eq(BusOrder.class, "deptId");
        cq.eq(BusOrder.class, "supplierBondType");
        cq.eq(BusOrder.class, "customBondType");
        //排除未提交
        cq.ne("ord.orderState", CommonConstants.INT_0);
        cq.eq(BusCustom.class, "areaName");
        cq.like(BusCustom.class, "customName");
        cq.like(BusSupplier.class, "supplierName");
        cq.like(BusDrugs.class, "drugsName");
        if (FlymeUtils.isNotEmpty(beginDate)) {
            cq.ge(BusOrderDetails.class, "saleDate", beginDate);
        }
        if (FlymeUtils.isNotEmpty(endDate)) {
            cq.le(BusOrderDetails.class, "saleDate", endDate);
        }
        if (FlymeUtils.isNotEmpty(refundDate1)) {
            cq.ge(BusOrderDetails.class, "supplierRetDate", refundDate1);
        }
        if (FlymeUtils.isNotEmpty(refundDate2)) {
            cq.le(BusOrderDetails.class, "supplierRetDate", refundDate2);
        }
        if (FlymeUtils.isNotEmpty(returnDate1)) {
            cq.ge(BusOrderDetails.class, "returnDate", returnDate1);
        }
        if (FlymeUtils.isNotEmpty(returnDate2)) {
            cq.le(BusOrderDetails.class, "returnDate", returnDate2);
        }
        if (FlymeUtils.isNotEmpty(supplierBondState)) {
            cq.in(true, "supplierBondState", supplierBondState.split(","));
        }
        if (FlymeUtils.isNotEmpty(customReturnState)) {
            cq.in(true, "customReturnState", customReturnState.split(","));
        }
        if (FlymeUtils.isNotEmpty(supplierRefundState)) {
            cq.in(true, "supplierRefundState", supplierRefundState.split(","));
        }
        if (FlymeUtils.isNotEmpty(customBondState)) {
            cq.in(true, "customBondState", customBondState.split(","));
        }
        if (FlymeUtils.isNotEmpty(settleState)) {
            cq.in(true, "settleState", settleState.split(","));
        }
        if (FlymeUtils.isNotEmpty(saleType)) {
            cq.in(true, "saleType", saleType.split(","));
        }
        if (errorType.equals(1)) {
            cq.apply("bod.saleAmount!=bod.invoiceAmount and bod.invoiceAmount>0");
        }
        if (errorType.equals(2)) {
            cq.apply("bod.settleAmount!=bod.settleRealAmount and bod.settleRealAmount!=0");
        }
        if (errorType.equals(3)) {
            cq.apply("bod.settleAmount2!=bod.settleRealAmount2 and bod.settleRealAmount2!=0");
        }
        if (errorType.equals(4)) {
            cq.apply("bod.supplierRetable!=bod.supplierRealAmount and bod.supplierRealAmount!=0");
        }
        if (errorType.equals(5)) {
            cq.apply("(bod.customBond+bod.customOverBond)!=bod.returnCustomBond and bod.returnCustomBond!=0");
        }
        if (errorType.equals(6)) {
            cq.apply("bod.supplierBond!=bod.supplierPayBond and bod.supplierPayBond!=0");
        }
        if (errorType.equals(7)) {
            cq.apply("bod.supplierPayBond!=bod.returnSupplierBond and bod.returnSupplierBond!=0");
        }
        cq.eq(true, "bod.companyId", companyId);
        cq.addSelect(BusOrder.class, "orderNo", "remark", "sendDate", "supplierBondType", "customBondType", "takeDate");
        cq.addSelect(BusDept.class, "deptName");
        cq.addSelect(BusSaleman.class, "saleManName");
        cq.createJoin(BusDept.class);
        cq.createJoin(BusSaleman.class);

    }

    @Override
    public List<EntityMap> complete(CriteriaQuery<BusOrderDetails> cq, List<EntityMap> result, EntityMap extra) {
        for (EntityMap entityMap : result) {
            Long orderDetailsId = entityMap.getLong("orderDetailsId");
            getSupplierBondState(entityMap);
            getCustomReturnState(entityMap);
            getCustomBond(entityMap);
            getSupplierRefundState(entityMap);
            getSettleState(entityMap);
        }
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isNotEmpty(userId)) {
            cq.setExportKey("report:" + userId);
        }
        return result;
    }

    /**
     * 查询垫付款状态
     */
    private Boolean getSupplierBondState(EntityMap entityMap) {
        //垫付方式
        Integer supplierBondType = entityMap.getInt("supplierBondType");
        Integer saleType = entityMap.getInt("saleType");
        Integer sbState = entityMap.getInt("supplierBondState");
        String supplierRetBondDate = entityMap.get("supplierRetBondDate");
        BigDecimal supplierPayBond = entityMap.getBigDecimal("supplierPayBond");
        //垫付款状态
        String supplierBondState = "";
        if (supplierBondType > 0 && (saleType.equals(1) || saleType.equals(3))) {
            if (sbState.equals(0)) {
                supplierBondState = "未支付";
            }
            if (sbState.equals(2)) {
                supplierBondState = "已支付";
            }
            if (sbState.equals(1)) {
                supplierBondState = "审批中";
            }
            if (sbState.equals(3)) {
                supplierBondState = "已退款";
            }

        } else {
            supplierBondState = "-";
            entityMap.put("returnSupplierBond", "0");
        }

        entityMap.put("supplierPayBond", supplierPayBond);
        entityMap.put("supplierBondState", supplierBondState);
        if (FlymeUtils.isNotEmpty(supplierRetBondDate)) {
            entityMap.put("supplierRetBondDate", DateUtils.formatDate(DateUtils.parseDate(supplierRetBondDate), "yyyy-MM-dd"));
        }
        return true;
    }


    /**
     * 查询资保金收款
     */
    private Boolean getCustomBond(EntityMap entityMap) {
        //销售类型
        Integer saleType = entityMap.getInt("saleType");
        Long orderId = entityMap.getLong("orderId");
        BigDecimal customBond = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("customBond"), "0");
        BigDecimal overAmount = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("customOverBond"), "0");
        Integer cbState = entityMap.getInt("customBondState");
        String customBondState = "";
        String takeDate = "";
        BigDecimal customBondTake = new BigDecimal("0");
        BusOrder order = orderService.getById(orderId);
        if (FlymeUtils.isNotEmpty(order)) {
            takeDate = DateUtils.formatDate(order.getTakeDate(), "yyyy-MM-dd");
        }
        //资保金方式
        Integer customBondType = entityMap.getInt("customBondType");
        if (customBondType > 0 && !customBondType.equals(7) && !customBondType.equals(5) && saleType.equals(SaleTypeEnum.Xs.getCode())) {
            //保证金状态
            customBondTake = overAmount.add(customBond);
            if (cbState.equals(1)) {
                customBondState = "已认款";
            }
            if (cbState.equals(0)) {
                customBondState = "未认款";
            }
        } else {
            if (customBondType.equals(0)) {
                if (FlymeUtils.isNotEmpty(order)) {
                    //全款回款日期
                    //entityMap.put("returnDate", takeDate);
                }
            }
            takeDate = "-";
            customBondTake = overAmount.add(customBond);
            customBondState = "-";
        }
        BigDecimal returnCustomBond = entityMap.getBigDecimal("returnCustomBond");
        String customBondRetDate = entityMap.get("customBondRetDate");
        if (cbState.equals(2)) {
            customBondState = "已退款";
        }
        entityMap.put("returnCustomBondDate", customBondRetDate);
        entityMap.put("takeDate", takeDate);
        entityMap.put("customBond", customBond);
        entityMap.put("overAmount", overAmount);
        entityMap.put("customBondTake", customBondTake);
        entityMap.put("customBondState", customBondState);
        return true;
    }


    /**
     * 查询市场回款状态
     */
    private Boolean getCustomReturnState(EntityMap entityMap) {
        Long orderDetailsId = entityMap.getLong("orderDetailsId");
        EntityMap resultMap = new EntityMap();
        //订单类型
        Integer saleType = entityMap.getInt("saleType");
        //回款金额
        BigDecimal returnAmount = entityMap.getBigDecimal("returnAmount");
        String returnDate = FlymeUtils.getString(entityMap.get("returnDate"));
        //回款状态
        String customReturnState = "未回款";
        if (SaleTypeEnum.Xs.getCode().equals(saleType)) {
            if (FlymeUtils.gtzero(returnAmount)) {
                customReturnState = "已回款";
            }
        }
        if (!saleType.equals(1)) {
            if (FlymeUtils.nezero(returnAmount)) {
                if (saleType.equals(SaleTypeEnum.Th.getCode())) {
                    customReturnState = "已退款";
                }
                if (saleType.equals(SaleTypeEnum.Bh.getCode())) {
                    customReturnState = "已回款";
                }
            }
        }
        resultMap.put("customReturnState", customReturnState);
        resultMap.put("returnAmount", returnAmount);
        resultMap.put("returnDate", returnDate);
        entityMap.putAll(resultMap);
        return true;
    }

    /**
     * 查询厂家返款和开票状态
     */
    private Boolean getSupplierRefundState(EntityMap entityMap) {
        Long kaipiaoId = entityMap.getLong("kaipiaoId");
        //返款状态
        Integer supplierRefundState = entityMap.getInt("supplierRefundState");
        EntityMap resultMap = new EntityMap();
        String supplierRefundStateText = "未返款";
        String supplierRefundAmountDate = "";
        Integer saleType = entityMap.getInt("saleType");
        BigDecimal invoicePaymentAmount = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("invoicePaymentAmount"), "0");
        BigDecimal invoiceSj = FlymeUtils.getBigDecimal(entityMap.getBigDecimal("invoiceSj"), "0");
        String invoiceAmountDate = FlymeUtils.getString(entityMap.get("invoiceAmountDate"), "");
        String invoicePaymentNo = FlymeUtils.getString(entityMap.get("invoicePaymentNo"), "");
        String invoiceunitName = FlymeUtils.getString(entityMap.get("invoiceunitName"), "");
        if (supplierRefundState.equals(1)) {
            supplierRefundStateText = "已开票";
        }
        BigDecimal supplierRefundAmount = entityMap.getBigDecimal("supplierRealAmount");
        //计算返款
        if (FlymeUtils.isNotEmpty(supplierRefundAmount)&&FlymeUtils.nezero(supplierRefundAmount)) {
            supplierRefundStateText = "已返款";
            supplierRefundAmountDate = entityMap.get("supplierRetDate");
        }
        resultMap.put("invoiceunitName", invoiceunitName);
        resultMap.put("invoicePaymentAmount", invoicePaymentAmount);
        resultMap.put("invoiceSj", invoiceSj);
        resultMap.put("invoiceAmountDate", invoiceAmountDate);
        resultMap.put("invoicePaymentNo", invoicePaymentNo);
        resultMap.put("supplierRefundState", supplierRefundStateText);
        resultMap.put("supplierRefundAmount", supplierRefundAmount);
        resultMap.put("supplierRefundAmountDate", supplierRefundAmountDate);

        entityMap.putAll(resultMap);
        return true;
    }

    /**
     * 查询结算状态
     */
    private Boolean getSettleState(EntityMap entityMap) {
        EntityMap resultMap = new EntityMap();
        String settleState = "未结算";
        Long orderDetailsId = entityMap.getLong("orderDetailsId");
        //销售类型
        Integer saleType = entityMap.getInt("saleType");
        BigDecimal settleAmount = entityMap.getBigDecimal("settleAmount");
        BigDecimal settleRealAmount = entityMap.getBigDecimal("settleRealAmount");
        BigDecimal settleAmount2 = entityMap.getBigDecimal("settleAmount2");
        BigDecimal settleAmount3 = entityMap.getBigDecimal("settleAmount3");
        BigDecimal settleRealAmount2 = entityMap.getBigDecimal("settleRealAmount2");
        BigDecimal settleRealAmount3 = entityMap.getBigDecimal("settleRealAmount3");
        Integer state = entityMap.getInt("settleState");
        Integer state2 = entityMap.getInt("settleState2");
        Integer state3 = entityMap.getInt("settleState3");
        Integer state4 = state + state2 + state3;
        //未结算金额=0
        if (state.equals(2)) {
            settleState = "已结算";
        }
        entityMap.put("settleAmount", settleAmount);
        entityMap.put("settleRealAmount", settleRealAmount);
        entityMap.put("settleAmount2", settleAmount2);
        entityMap.put("settleRealAmount2", settleRealAmount2);
        entityMap.put("settleRealAmount3", settleRealAmount3);
        entityMap.put("settleState", settleState);
        return true;

    }


    @Override
    public void initExcelExportEntity(ExportField exportField, List list) {
        Object key = exportField.getKey();
        if (key.equals("orderNo")) {
            exportField.setWidth(15);
        }
        if (key.equals("invoiceAmount")) {
            exportField.setMergeVertical(true);
        }

    }


    @Override
    public TemplateExportParams initTemplateExportParams(Map params) {
        Long companyId=OpenHelper.getCompanyId();
        TemplateExportParams templateExportParams = new TemplateExportParams("excel/模板订单明细表"+companyId+".xlsx", true);
        return templateExportParams;
    }

    @Override
    public Map initTemplateDataMap() {
        HashMap<Object, Object> dataMap = new HashMap<>();

        return dataMap;
    }

    @Override
    public void initExportData(Map dataMap, List list,CriteriaQuery cq) {
        Map<String,BigDecimal> mapTotal=new HashMap<>();
        if(FlymeUtils.isNotEmpty(list)){
            BigDecimal totalInvoicePaymentAmount=new BigDecimal("0");
            BigDecimal totalInvoiceSj=new BigDecimal("0");
            for (Object o : list) {
                EntityMap map= (EntityMap) o;
                String invoicePaymentNo = FlymeUtils.getString(map.get("invoicePaymentNo"), "");
                BigDecimal invoicePaymentAmount = FlymeUtils.getBigDecimal(map.getBigDecimal("invoicePaymentAmount"), "0");
                BigDecimal invoiceSj = FlymeUtils.getBigDecimal(map.getBigDecimal("invoiceSj"), "0");
                BigDecimal amount=mapTotal.get(invoicePaymentNo);
                if(FlymeUtils.isEmpty(amount)){
                    totalInvoicePaymentAmount=totalInvoicePaymentAmount.add(invoicePaymentAmount);
                    totalInvoiceSj=totalInvoiceSj.add(invoiceSj);
                    mapTotal.put(invoicePaymentNo,invoicePaymentAmount);
                }
            }
            dataMap.put("totalInvoicePaymentAmount",totalInvoicePaymentAmount);
            dataMap.put("totalInvoiceSj",totalInvoiceSj);
        }
    }
}
